import mysql.connector
from mysql.connector import Error
import traceback


class DBUtils:
    """数据库工具类 - 稳定版"""

    def __init__(self):
        self.connection = None
        self._connect()  # 初始化时立即尝试连接

    def _connect(self):
        """建立数据库连接"""
        try:
            # 创建新连接
            self.connection = mysql.connector.connect(
                host='localhost',
                database='bank system',
                user='root',
                password='1234',
                autocommit=True,
                connect_timeout=5  # 添加连接超时
            )

            if self.connection.is_connected():
                print(f"成功连接到MySQL服务器 (版本 {self.connection.server_version})")
                return True
            return False

        except Error as e:
            print(f"数据库连接失败: {e}")
            traceback.print_exc()
            raise ConnectionError(f"无法连接数据库: {str(e)}")

    def is_connected(self):
        """检查连接状态"""
        try:
            return self.connection and self.connection.is_connected()
        except:
            return False

    def execute_query(self, query, params=None, fetch=True):
        """执行SQL查询"""
        cursor = None
        try:
            # 确保连接有效
            if not self.is_connected():
                print("连接已断开，尝试重新连接...")
                if not self._connect():
                    print("无法重新连接到数据库")
                    return None

            cursor = self.connection.cursor(dictionary=True)
            cursor.execute(query, params or ())

            if fetch:
                result = cursor.fetchall()
                return result if result else []
            else:
                self.connection.commit()
                return True

        except Error as e:
            print(f"查询执行失败: {e}")
            traceback.print_exc()
            if self.connection:
                self.connection.rollback()
            return None
        finally:
            if cursor:
                cursor.close()

    def disconnect(self):
        """安全关闭连接"""
        if self.is_connected():
            try:
                self.connection.close()
                print("数据库连接已关闭")
            except Error as e:
                print(f"关闭连接时出错: {e}")
        self.connection = None

    def __del__(self):
        self.disconnect()